<template>
  <div>
        <h1>axios和json综合</h1>
        <input type="button" value="请求和响应都是普通字符串" @click="method01()"> <br>
        <input type="button" value="响应数据改成json字符串" @click="method02()"> <br>
        <input type="button" value="请求数据也改成json字符串" @click="method03()"> <br>
        <hr>
        <h3>好友列表</h3>
        <div id="messageDiv"></div>
        <table width="500px" cellspacing="0px" cellpadding="5px" border="1px" id="myTable">
            <tr>
                <th>id</th>
                <th>name</th>
                <th>age</th>
            </tr>
            <!-- <tr>
                <td></td>
                <td></td>
                <td></td>
            </tr>-->
        </table>
  </div>
       
</template>

<script>
import axios from 'axios'
export default {
  methods: {
    //1.请求和响应都是普通字符串
    method01(){
      let url="/demo01Servlet";
      let params=`username=柳岩&password=1234`;
      axios.post(url,params)
           .then(resp=>{
            console.log(resp.data);
           });

    },
    //2.请求是普通字符串，响应数据改成json字符串
    method02(){
      let url="/demo02Servlet";
      let params=`username=柳岩&password=1234`;
      axios.post(url,params)
           .then(resp=>{
              let content = "";
              let arr = resp.data;
              for(let l of arr){
                content +=`<tr>
                                <td>${l.id}</td>
                                <td>${l.name}</td>
                                <td>${l.age}</td>
                          </tr>`;
              }
              document.getElementById("myTable").innerHTML +=content;
           });
    },
    //3.请求是json字符串，响应数据改成json字符串
    method03(){
      //3.1准备url
        let url="/demo03Servlet";
        //3.2准备请求参数
        let params ={"username":"电锯人","password":"5555"}
        //3.3发送异步请求
        axios.post(url,params)
             .then(resp=>{
              //3.4 定义变量接收后端响应的json数组
               let obj = resp.data;
               //查询成功 <div id="messageDiv"></div>
               document.getElementById("messageDiv").innerHTML=obj.message;
               //判断
               if(obj.flag){
                //将响应数据放到table标签中
                let arr = obj.valueData;
                //3.5定义变量保存从数组中取出的每行数据
                let content = "";
                //3.6遍历数组arr
                for(let friend of arr){
                  //3.7取出的内容拼接到变量content
                  content +=`<tr>
                                <td>${friend.id}</td>
                                <td>${friend.name}</td>
                                <td>${friend.age}</td>
                          </tr>`
                }
                //3.8将content内容放到table标签中
                document.getElementById("myTable").innerHTML += content;//查询成功 <div id="messageDiv"></div>
               }else{
                document.getElementById("messageDiv").innerHTML=obj.message;//查询失败 <div id="messageDiv"></div>
               }
             });
    }
  }
}
</script>

<style>

</style>
